// Copyright (c) 2022 NetEase, Inc. All rights reserved.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.

import 'dart:async';

import 'package:baselib/utils/image_util.dart';
import 'package:baselib/utils/log_util.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:framelib/utils/drawable_util.dart';
import 'package:framelib/utils/string_util.dart';
import 'package:nim_core/nim_core.dart';
import 'package:get/get.dart';
class RecordPanel extends StatefulWidget {
  RecordPanel(
      {Key key,
       this.onPressedDown,
       this.onEnd,
       this.onCancel,
       this.audioMessageCallBack,
      })
      : super(key: key);

   VoidCallback onPressedDown;
   VoidCallback onEnd;
   VoidCallback onCancel;
   Function audioMessageCallBack;

  @override
  State<StatefulWidget> createState() => _RecordPanelState();
}

class _RecordPanelState extends State<RecordPanel> {
  bool _recordOnPressed = false;
  OverlayEntry _overlayEntry;
  StreamSubscription _streamSubscription;

  AudioService get _audioService => NimCore.instance.audioService;
  Timer _timer;
  RxInt _duration = 60.obs;



  void buildOverlay(BuildContext context) {
    if (_overlayEntry == null) {
      _overlayEntry = OverlayEntry(builder: (context) {
        return Obx(() => Container(
          color: Colors.transparent,
          child: Center(
            child: Text(
              '${_duration.value}',
              style: TextStyle(
                  fontSize: 56,
                  color: Colors.white,
                  decoration: TextDecoration.none
              ),
            ),
          ),
        ));
      });
      Overlay.of(context).insert(_overlayEntry);
    }
  }

  void removeOverlay() {
    if (_overlayEntry != null) {
      _overlayEntry.remove();
      _overlayEntry = null;
    }
    if(_timer?.isActive??false){
      _timer?.cancel();
      _duration.value = 60;
    }
  }

  @override
  void initState() {
    super.initState();
    _streamSubscription =
        _audioService.onAudioRecordStatus.listen((recordInfo) {
      if(recordInfo.recordState == RecordState.START){
        LogUtil.d('onAudioRecordStatus--->START ');
        if(_recordOnPressed){
          _timer = Timer.periodic(Duration(milliseconds: 1000), (t) {
            _duration.value = _duration.value-1;
            LogUtil.d('onAudioRecordStatus--->duration=${_duration.value}');
          });
          // showVoiceView();
        }else{
          // hideVoiceView();
        }
      }
      if (recordInfo.recordState == RecordState.REACHED_MAX ||
          recordInfo.recordState == RecordState.SUCCESS) {
        // reached max time or success
        _recordOnPressed = false;
        widget.onEnd();
        if(_timer?.isActive??false)_timer?.cancel();
        setState(() {});
      }
      if (recordInfo.recordState == RecordState.SUCCESS &&
          recordInfo.filePath != null &&
          recordInfo.fileSize != null &&
          recordInfo.duration != null) {
        if(widget.audioMessageCallBack!=null)widget.audioMessageCallBack(
            recordInfo.filePath, recordInfo.fileSize, recordInfo.duration);
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _streamSubscription.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.topCenter,
      children: [
        Positioned(
          top: 30,
          child: Visibility(
              visible: _recordOnPressed, child: const RecordButtonWave()),
        ),
        Positioned(
          top: 30,
          child: Column(
            children: [
              GestureDetector(
                onLongPressCancel: () {
                  _recordOnPressed = false;
                  removeOverlay();
                  _audioService.cancelRecord();
                  widget.onCancel();
                  setState(() {});
                },
                onLongPressDown: (LongPressDownDetails details) {
                  _recordOnPressed = true;
                  _audioService.startRecord(AudioOutputFormat.AAC, 60);
                  buildOverlay(context);
                  widget.onPressedDown();
                  setState(() {});
                },
                onLongPressEnd: (LongPressEndDetails details) {
                  _recordOnPressed = false;
                  removeOverlay();
                  double r = 51.5;
                  double dx = (details.localPosition.dx - r).abs();
                  double dy = (details.localPosition.dy - r).abs();
                  if (dx * dx + dy * dy > r * r) {
                    _audioService.cancelRecord();
                    widget.onCancel();
                  } else {
                    _audioService.stopRecord();
                    widget.onEnd();
                  }
                  setState(() {});
                },
                child: Container(
                  padding: const EdgeInsets.all(33.5),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(51.5),
                      gradient: const LinearGradient(
                          colors: [Color(0xff6aa1ff), Color(0xff3479ee)])),
                  child: ImagesUtil.loadAssetImage(
                      DrawableUtil.instance.icon_room_voice_speak_open,
                      width: 36,
                      color: _recordOnPressed? const Color(0x7fffffff): Colors.white,
                  )
                  // SvgPicture.asset(
                  //   'images/ic_record.svg',
                  //   package: 'nim_chatkit_ui',
                  //   width: 36,
                  //   height: 36,
                  //   color: _recordOnPressed? const Color(0x7fffffff): Colors.white,
                  // ),
                ),
              ),
              const SizedBox(
                height: 12,
              ),
              Text(
                _recordOnPressed ? "" : StringUtil.instance.Please_press_to_speak,
                style: const TextStyle(
                    fontSize: 12, color: Color(0xff999999)),
              )
            ],
          ),
        ),
      ],
    );
  }
}

class RecordButtonWave extends StatefulWidget {
  const RecordButtonWave({Key key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _RecordButtonWaveState();
}

class _RecordButtonWaveState extends State<RecordButtonWave>
    with SingleTickerProviderStateMixin {
   AnimationController _controller;
   Animation<double> _widthAnimation;

  @override
  void initState() {
    _controller = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 1000))
      ..repeat();

    _widthAnimation = Tween(begin: 1.0, end: 1.5)
        .animate(CurvedAnimation(parent: _controller, curve: Curves.ease));

    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ScaleTransition(
      scale: _widthAnimation,
      child: Container(
        height: 103,
        width: 103,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(51.5),
            color: const Color(0x4d518ef8)),
      ),
    );
  }
}
